﻿using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using Microsoft.Phone.Reactive;
using Newtonsoft.Json;
using TimeTracker.Models;
using TimeTracker.Phone;

namespace TimeTracker.PhoneApp
{
    public class MainViewModel : NotifyPropertyChangedBase
    {
        //TODO: Remember to change this as the phone must know where to connect to. Usually this is going to be an external service. 
        public const string ServerName = "localhost";

        public static string GetAllEntriesAction = string.Format("http://{0}/time-tracker/entry/getall", ServerName);
        public static string ContinueAction = string.Format("http://{0}/time-tracker/entry/continue/", ServerName);
        public static string StopAction = string.Format("http://{0}/time-tracker/entry/stop/", ServerName);        


        public MainViewModel()
        {
            this.Items = new ObservableCollection<EntryViewModel>();
        }

        /// <summary>
        /// A collection for ItemViewModel objects.
        /// </summary>
        public ObservableCollection<EntryViewModel> Items { get; private set; }

        public bool IsDataLoaded
        {
            get;
            private set;
        }

        /// <summary>
        /// Creates and adds a few ItemViewModel objects into the Items collection.
        /// </summary>
        public void LoadData()
        {
            this.Items.Clear();

            var wc = new WebClient();
            var o = Observable.FromEvent<DownloadStringCompletedEventHandler, DownloadStringCompletedEventArgs>(
                                ev => new DownloadStringCompletedEventHandler(ev),
                                ev => wc.DownloadStringCompleted += ev,
                                ev => wc.DownloadStringCompleted += ev)
                // Let's make sure that we’re on the thread pool                          
                .ObserveOn(Scheduler.ThreadPool)
                // When the event fires, just select the string and make                      
                // an IObservable<string> instead                      
                .SelectMany(x => JsonConvert.DeserializeObject<EntryModel[]>(x.EventArgs.Result))
                // Now go back to the UI Thread                      
                .ObserveOnDispatcher()
                // Subscribe to the observable, and set the label text                      
                .Subscribe(ShowEntry);

            wc.DownloadStringAsync(new Uri(GetAllEntriesAction));

            this.IsDataLoaded = true;
        }

        public void Start(EntryViewModel entry)
        {
            var wc = new WebClient();
            var o = Observable.FromEvent<DownloadStringCompletedEventHandler, DownloadStringCompletedEventArgs>(
                                ev => new DownloadStringCompletedEventHandler(ev),
                                ev => wc.DownloadStringCompleted += ev,
                                ev => wc.DownloadStringCompleted += ev)
                // Let's make sure that we’re on the thread pool                      
                .ObserveOn(Scheduler.ThreadPool)
                // When the event fires, just select the string and make                      
                // an IObservable<string> instead                      
                .Select(x => JsonConvert.DeserializeObject<EntryModel>(x.EventArgs.Result))
                // Now go back to the UI Thread                      
                .ObserveOnDispatcher()
                // Subscribe to the observable, and set the label text                      
                .Subscribe(x => UpdateWithEntry(entry, x));

            wc.DownloadStringAsync(new Uri(ContinueAction + entry.Id));
        }

        public void Stop(EntryViewModel entry)
        {
            var wc = new WebClient();
            var o = Observable.FromEvent<DownloadStringCompletedEventHandler, DownloadStringCompletedEventArgs>(
                                ev => new DownloadStringCompletedEventHandler(ev),
                                ev => wc.DownloadStringCompleted += ev,
                                ev => wc.DownloadStringCompleted += ev)
                // Let's make sure that we’re on the thread pool                      
                .ObserveOn(Scheduler.ThreadPool)
                // When the event fires, just select the string and make                      
                // an IObservable<string> instead                      
                .Select(x => JsonConvert.DeserializeObject<EntryModel>(x.EventArgs.Result))
                // Now go back to the UI Thread                      
                .ObserveOnDispatcher()
                // Subscribe to the observable, and set the label text                      
                .Subscribe(x => UpdateWithEntry(entry, x));

            wc.DownloadStringAsync(new Uri(StopAction + entry.Id));
        }

        private void ShowEntry(EntryModel model)
        {
            this.Items.Add(new EntryViewModel(this, model));

            Notify("GroupedItems");
            Notify("SortedItems");
        }

        private void UpdateWithEntry(EntryViewModel entry, EntryModel model)
        {
            if (entry.Id == model.Id)
            {
                entry.UpdateViewModel(model);
            }
            else
            {
                this.Items.Add(new EntryViewModel(this, model));
            }

            Notify("GroupedItems");
            Notify("SortedItems");
        }

        public ICollectionView SortedItems
        {
            get
            {
                var sortedCollection = new CollectionViewSource();
                sortedCollection.SortDescriptions.Add(new SortDescription("IsActive", ListSortDirection.Descending));
                sortedCollection.SortDescriptions.Add(new SortDescription("LastStartTime", ListSortDirection.Descending));
                sortedCollection.Source = Items;

                return sortedCollection.View;
            }
        }

        public class GroupingLayer<TKey, TElement> : IGrouping<TKey, TElement>
        {
            private readonly IGrouping<TKey, TElement> grouping;

            public GroupingLayer(IGrouping<TKey, TElement> unit)
            {
                grouping = unit;
            }

            public TKey Key
            {
                get { return grouping.Key; }
            }

            public IEnumerator<TElement> GetEnumerator()
            {
                return grouping.GetEnumerator();
            }

            System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
            {
                return grouping.GetEnumerator();
            }
        }

        public IEnumerable<IGrouping<string, EntryViewModel>> GroupedItems
        {
            get
            {
                var selected = from c in Items
                               orderby c.LastStartTime descending
                               orderby c.IsActive descending
                               group c by c.CompleteProject into n
                               select new GroupingLayer<string, EntryViewModel>(n);

                return selected.Cast<IGrouping<string, EntryViewModel>>();
            }
        }
    }
}